import { login, logout, getInfo, getMenus,oauthToken } from '@/api/login';
import { getToken, setToken, removeToken } from '@/assets/js/auth';
import avatar_default1 from '@/assets/images/gender1.png';
import avatar_default2 from '@/assets/images/gender2.png';
import tab from './tab';
import router from '@/router';
import util from '@/assets/js/public';
import { getUserdata } from '@/api/gettodo'
const user = {
	state: {
		tabnav: tab.tabnav,
		token: getToken(),
		refreshToken:'',
		//avatar:'',
		// user: {},
		user: { userName:'wangshuai'},
		roles: [],
		menus: [],
    // userinfo:[],
		userinfo:{userName:'liushifeng',
    truename:'刘世锋',preferredMobile:"13837151605",authOrgs:[{displayName:"省公司\\党委办公室（党群工作部）"}],authRoles: [
				{
					"id": "djfupt_001",
					"roleCode": "djfupt_001",
					"roleName": "省公司管理员",
					"isApplicationRole": true,
					"displayOrder": 1,
					"authority": "djfupt_001"
				}]},
		haszcxjmenu:{},
		hassetmenuadd:{},
		hassetmenu:{},
		haswtsbmenu:{},
		hasjytgmenu:{}
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token;
			setToken(token);
		},
		SET_REFRESHTOKEN:(state,refreshToken) => {
		   state.refreshToken=refreshToken
		},
		SET_USER: (state, user) => {
			state.user = user;
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles;
		},
		SET_MENUS: (state, menus) => {
			state.menus = menus;
		},
		CLOSE_TABALL: state => {
			state.tabnav = [];
		},
		SET_USERINFO: (state, userinfo) => {
			state.userinfo = userinfo;
		},
		HAS_ZCXJ_MENU: (state, haszcxjmenu) => {
			state.haszcxjmenu = haszcxjmenu;
		},
		HAS_SET_MENU_ADD: (state, hassetmenuadd) => {
			state.hassetmenuadd = hassetmenuadd;
		},
		HAS_SET_MENU_SET: (state, hassetmenu) => {
			state.hassetmenu = hassetmenu;
		},
		HAS_WTSB_MENU: (state, haswtsbmenu) => {
			state.haswtsbmenu = haswtsbmenu;
		},
		HAS_JYTG_MENU: (state, hasjytgmenu) => {
			state.hasjytgmenu = hasjytgmenu;
		},
	},
	actions: {
		//设置token
		SetToken({ commit }) {
			return new Promise((resolve,reject)=>{
				let params = {
					client_id:'c1ebe466-1cdc-4bd3-ab69-77c3561b9dee',
					client_secret:'d8346ea2-6017-43ed-ad68-19c0f971738b',
					grant_type:'refresh_token',
					refresh_token:user.state.refreshToken
				}
				console.log(params)
				oauthToken(params).then(response=>{
					commit('SET_TOKEN', response.data.accessToken);
					commit('SET_REFRESHTOKEN', response.data.refreshToken);
					resolve(response);
				}).catch(error=>{
					reject(error);
				});
			});
		},
		//设置刷新token的参数
		SetRefreshToken({ commit },data) {
			return new Promise((resolve,reject)=>{
				console.log('设置token啊啊',data)
				if(data){
					console.log(util.aesDecrypt(data.userName));
					commit('SET_REFRESHTOKEN', data.refreshToken);
					commit('SET_TOKEN', data.accessToken);
					commit('SET_USER', {userName:util.aesDecrypt(data.userName)});
					resolve('获取token成功');
				}else{
					reject('获取token失败');
				}
			});
		},
		//登录
		Login({ commit }, userinfo) {
			console.log(userinfo)
			const phone = userinfo.phone?.trim();
			const smscode = userinfo.smscode?.trim();
			return new Promise((resolve, reject) => {
				let params={phone,grant_type:'phone',scope:'all',client_id:'iservice_maip',client_secret:process.env.VUE_APP_SECRET,appcode:'maip'};
				if(smscode){
					params.smscode=smscode;
					params.grant_type='phonecode';
				} 
				// let params={phone,appcode:'maip'};
				if(phone){
					login(params).then(response => {
						const data = response;
						const tokenStr = data.access_token;
						commit('SET_TOKEN', tokenStr);
						resolve(response);
					})
					.catch(error => {
						reject(error);
					});
				}else{
					reject({message:'手机号必传！'});
				}
			});
		},
		//获取用户信息
		GetInfo({ commit },data) {
			return new Promise((resolve,reject)=>{
				console.log(util.aesDecrypt(data.userName));
				getUserdata(Object.assign({
					userName:util.aesDecrypt(data.userName)})).
					then((result)=>{
						if (!result.data) {
							reject({message:'获取用户基础信息失败！'});
							return;
						}
						let hasmenu1 = false;
						let hasmenu2 = false;
						let hasmenu3 = false;
						let hasmenu4 = false;
						let hasmenu5 = false;
						if(result.data.data.authPermissions){
							for(var i = 0; i<result.data.data.authPermissions.length;i++){
								if(result.data.data.authPermissions[i].description=='政策宣讲下达'){
									hasmenu1 = true;
								}
								if(result.data.data.authPermissions[i].description=='思政纪实填报'){
									hasmenu2 = true;
								}
								if(result.data.data.authPermissions[i].description=='思政纪实配置'){
									hasmenu5 = true;
								}
								if(result.data.data.authPermissions[i].description=='问题上报'){
									hasmenu3 = true;
								}
								if(result.data.data.authPermissions[i].description=='经验推广填报'){
									hasmenu4 = true;
								}
							
							}
						}
						if(hasmenu1){
							commit('HAS_ZCXJ_MENU', true);
						}else{
							commit('HAS_ZCXJ_MENU', false);
						}
						if(hasmenu2){
							commit('HAS_SET_MENU_ADD', true);
						}else{
							commit('HAS_SET_MENU_ADD', false);
						}
						if(hasmenu5){
							commit('HAS_SET_MENU_SET', true);
						}else{
							commit('HAS_SET_MENU_SET', false);
						}
						if(hasmenu3){
							commit('HAS_WTSB_MENU', true);
						}else{
							commit('HAS_WTSB_MENU', false);
						}
						if(hasmenu4){
							commit('HAS_JYTG_MENU', true);
						}else{
							commit('HAS_JYTG_MENU', false);
						}
						commit('SET_USERINFO', result.data.data);
						resolve('获取用户基础信息完毕！');
					})
			});
			// return new Promise((resolve, reject) => {
			// 	getInfo()
			// 		.then(response => {						
			// 			let data = response.data;
			// 			if (data.authRoles && data.authRoles.length > 0) {
			// 				commit('SET_ROLES', data);
			// 			} else {
			// 				reject('getinfo: roles must be a non-null array !');
			// 			}
			// 			// commit('SET_NAME',data.username);
			// 			//commit('SET_AVATAR',data.icon || avatar_default);
			// 			data.preferredMobileI=data.preferredMobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			// 			data.photo = data.photo || (data.genderDictValue=='1'?avatar_default1:avatar_default2);
			// 			if ((!process.env.VUE_APP_APPCURRENTUSER) || (process.env.VUE_APP_APPCURRENTUSER && process.env.VUE_APP_APPCURRENTUSER === 'true')) {
			// 				data.currentBloc = data.schoolId || (data.authBlocs.length > 0 ? data.authBlocs[0].id : '');
			// 				data.currentCorp = data.zoneId || (data.authCorps > 0 ? data.authCorps[0].id : '');
			// 			}
			// 			//data.currentCorpName=data.authCorps[0].corpName;

			// 			commit('SET_USER', data);
			// 			resolve(response);
			// 		})
			// 		.catch(error => {
			// 			reject(error);
			// 		});
			// });
		},
		//登出
		LogOut({ commit, state }) {
			return new Promise((resolve, reject) => {
				logout(state.token)
					.then(response => {
						//commit('SET_AVATAR',data.icon);
						commit('SET_USER', {});
						commit('SET_MENUS', []);
						commit('CLOSE_TABALL');
						if (router.options.routes.length > 3)
							router.options.routes.splice(3);
						resolve(response);
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		//前端 登出
		FedLogOut({ commit }) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '');
				commit('SET_MENUS', []);
				commit('CLOSE_TABALL');
				removeToken();
				resolve();
			});
		},
		//获取菜单
		GetMenus({ commit, state }) {
			console.log('GetMenus');
			return new Promise((resolve, reject) => {			
				getMenus(state.user.username)
				.then(res => {
					commit('SET_MENUS', res.data);
					commit('CLOSE_TABALL');
					resolve(res);
				})
				.catch(error => {
					reject(error);
				});
			});
		}
	}
};
export default user;
